package com.shenhan.channel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * <br>
 *
 * <p>- <br>
 *
 * @author shenhan
 * @version 1.0
 * @date: 2022/5/16 15:29
 * @description:
 */
public class FileNIOCopyDemo {

  public static void main(String[] args) throws IOException {
    nioCopyResourceFile();
  }

  /**
   * 复制资源目录下的文件
   */
  public static void nioCopyResourceFile() throws IOException {
    String sourcePath = "D:\\Program Files (x86)\\develop\\project\\iodemo\\resources\\test.txt";
    String srcPath = "D:\\Program Files (x86)\\develop\\project\\iodemo\\resources\\test_target.txt";

    nioCopyFile(sourcePath, srcPath);
  }

  private static void nioCopyFile(String sourcePath, String srcPath) throws IOException {
    File srcFile = new File(sourcePath);
    File destFile = new File(srcPath);
    try {
      if (!destFile.exists()) {
        destFile.createNewFile();
      }
      FileInputStream fis = null;
      FileOutputStream fos = null;
      FileChannel inChannel = null;
      FileChannel outChannel = null;
      try {
        fis = new FileInputStream(srcFile);
        fos = new FileOutputStream(destFile);
        inChannel = fis.getChannel();
        outChannel = fos.getChannel();
        int length = -1;
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while ((length = inChannel.read(buffer)) != -1) {
          buffer.flip();
          int outLength = 0;
          while ((outLength = outChannel.write(buffer)) != 0) {
            System.out.println("写入的字节数：" + outLength);
          }
          buffer.clear();
        }
        outChannel.force(true);
      } finally {
        outChannel.close();
        fos.close();
        inChannel.close();
        fis.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

}
